package com.fc.mall.service.impl;

import com.fc.mall.dao.UmsAgentApplyDao;
import com.fc.mall.dto.UmsAgentCountStatusDto;
import com.fc.mall.dto.UmsAgentParam;
import com.fc.mall.exception.ServiceException;
import com.fc.mall.mapper.UmsAgentApplyMapper;
import com.fc.mall.mapper.UmsMemberMapper;
import com.fc.mall.model.UmsAgentApply;
import com.fc.mall.model.UmsMember;
import com.fc.mall.service.SmsNoticeService;
import com.fc.mall.service.UmsAgentService;
import com.fc.mall.util.Constants;
import com.fc.mall.util.DateTimeHelper;
import com.fc.mall.util.Utils;
import com.github.pagehelper.PageHelper;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.net.URLDecoder;
import java.util.Date;
import java.util.List;

/**
 * Created by Sunny on 2019/7/17.
 */
@Service
public class UmsAgentServiceImpl implements UmsAgentService {
    @Autowired
    private UmsAgentApplyMapper agentApplyMapper;

    @Autowired
    private UmsMemberMapper memberMapper;

    @Autowired
    private SmsNoticeService noticeService;

    @Autowired
    private UmsAgentApplyDao umsAgentApplyDao;

    @Override
    public List<UmsAgentApply> list(UmsAgentParam agentParam, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        if(!StringUtils.isEmpty(agentParam.getNickname())){
            agentParam.setNickname(Utils.urlEncoderTransfer(agentParam.getNickname()));
        }
        if(!StringUtils.isEmpty(agentParam.getNicknameOrPhone())){
            agentParam.setNicknameOrPhone(Utils.urlEncoderTransfer(agentParam.getNicknameOrPhone()));
        }
        if (!StringUtils.isEmpty(agentParam.getStartApplyDate())){
            Integer startApplyDate = DateTimeHelper.getEpochTimeInSecond(DateTimeHelper.getDateFromString(agentParam.getStartApplyDate(),DateTimeHelper.SQL_DATETIME));
            agentParam.setStartApplyDate(startApplyDate.toString());
        }
        if (!StringUtils.isEmpty(agentParam.getEndApplyDate())){
            Integer endApplyDate = DateTimeHelper.getEpochTimeInSecond(DateTimeHelper.getDateFromString(agentParam.getEndApplyDate(),DateTimeHelper.SQL_DATETIME));
            agentParam.setEndApplyDate(endApplyDate.toString());
        }
        List<UmsAgentApply> umsAgentApplyList = umsAgentApplyDao.queryList(agentParam);
        umsAgentApplyList.forEach(agentApply -> {
            try {
                String nickname = StringUtils.isEmpty(agentApply.getNickname()) ? "" : agentApply.getNickname();
                agentApply.setNickname(URLDecoder.decode(nickname, "utf-8"));
            }catch (Exception e)
            {

            }
        });

        return umsAgentApplyList;
    }

    @Override
    public void approveAgent(UmsAgentApply agentApply) {
        if(null == agentApply)
        {
            throw new ServiceException("申请不能为空");
        }

        UmsAgentApply oldagentApply = agentApplyMapper.selectByPrimaryKey(agentApply.getId());
        if(null == oldagentApply)
        {
            throw new ServiceException("申请不存在");
        }
        //申请通过
        if(agentApply.getStatus() == 2)
        {
            UmsMember currentUpgradeMember = new UmsMember();
            currentUpgradeMember.setId(agentApply.getMemberId());
            currentUpgradeMember.setLevelType(Constants.MemberLevelType.Agent.getValue());
            currentUpgradeMember.setMemberLevelId(2L);
            memberMapper.updateByPrimaryKeySelective(currentUpgradeMember);
        }
        agentApply.setApproveDate(DateTimeHelper.getEpochTimeInSecond(System.currentTimeMillis()));
        agentApplyMapper.updateByPrimaryKeySelective(agentApply);
        String status = agentApply.getStatus() == 2 ? "审核通过" : "审核失败：" + agentApply.getReason();
        sendApproveNotice(oldagentApply.getMemberId(), oldagentApply.getNickname(), status);
    }

    /**
     * 统计不同状态的数量
     * @return
     */
    @Override
    public UmsAgentCountStatusDto countStatus() {
        return umsAgentApplyDao.countStatus();
    }

    private void sendApproveNotice(Long memberId, String nickname, String status)
    {
        JSONObject json = new JSONObject();
        json.put("memberId", memberId);
        json.put("nickName", Utils.urlDecoderTransfer(nickname));
        json.put("type", "代理申请审核");
        json.put("status", status);
        json.put("approvalDate", DateTimeHelper.getStringFromDate(new Date(), DateTimeHelper.PAYLOAD_DATEONLY));
        json.put("noticeType", 3);
        noticeService.sendNotice(json.toString());
    }
}
